﻿using System;
using System.Collections.Generic;

using RexToy.Logging;
using RexToy.DesignPattern;

using MGAS.Model.Entity;

namespace MGAS.Model
{
    class SensorDataBlock : ISensorDataBlock
    {
        private static ILog _log = LogContext.GetLogger<SensorDataBlock>();

        public event EventHandler<SensorDataChangedEventArgs> SensorDataChanged;

        private Dictionary<byte, SensorData> _data;
        public SensorDataBlock()
        {
            _data = new Dictionary<byte, SensorData>();
            InitializeAddressList();
        }

        public void InitializeAddressList()
        {
            _data.Clear();
            foreach (var id in AllocMap.Instance().GetSensorIds())
            {
                _data.Add(id, SensorData.Create(id));
            }
        }

        public void UpdateData(byte id, int value, PressureUnit unit, PressureStatus status)
        {
            _log.Debug("Update data block [id={0}].", id);

            var s = _data[id];
            s.Value = value;
            s.Status = status;
            s.Unit = unit;

            if (SensorDataChanged != null)
            {
                SensorDataChangedEventArgs args = new SensorDataChangedEventArgs();
                args.Id = id;
                SensorDataChanged(this, args);
            }
        }

        public ISensorData GetData(byte id)
        {
            SensorData d;
            _data.TryGetValue(id, out d);
            return d;
        }
    }
}
